package cn.iocoder.yudao.module.ai.controller.admin.material;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.ai.controller.admin.material.vo.MaterialListVO;
import cn.iocoder.yudao.module.ai.controller.admin.materialreleasefile.vo.MaterialReleaseFileRespVO;
import cn.iocoder.yudao.module.ai.service.materialreleasefile.MaterialReleaseFileService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.servlet.http.HttpServletRequest;
import javax.validation.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.module.ai.controller.admin.material.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.material.MaterialDO;
import cn.iocoder.yudao.module.ai.service.material.MaterialService;

@Tag(name = "管理后台 - 素材管理")
@RestController
@RequestMapping("/ai/material")
@Validated
public class MaterialController {

    @Resource
    private MaterialService materialService;
    @Resource
    private MaterialReleaseFileService materialReleaseFileService;

    /**
     * 应用名
     */
    @Value("${material.access-path}")
    private String materialFilePrePath;

    @PostMapping("/create")
    @Operation(summary = "创建素材管理")
    @PreAuthorize("@ss.hasPermission('ai:material:create')")
    public CommonResult<Long> createMaterial(@Valid  MaterialSaveReqVO createReqVO) {
        if(null != createReqVO.getId()){
            return  error(CommonResult.error(500,"创建不能填写编号"));
        }
        Long data = materialService.saveMaterial(createReqVO);
        return success(data);
    }

    @PutMapping("/update")
    @Operation(summary = "更新素材管理")
    @PreAuthorize("@ss.hasPermission('ai:material:update')")
    public CommonResult<Boolean> updateMaterial(@Valid MaterialSaveReqVO updateReqVO) {
        if(null == updateReqVO.getId()){
            return  error(CommonResult.error(500,"编号不能为空"));
        }else{
            MaterialDO material = materialService.getMaterial(updateReqVO.getId());
            if(null == material){
                return  error(CommonResult.error(500,"素材不存在"));
            }
        }
        materialService.saveMaterial(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除素材管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:material:delete')")
    public CommonResult<Boolean> deleteMaterial(@RequestParam("id") Long id) {
        materialService.deleteMaterial(id);
        materialReleaseFileService.deleteByMaterialId(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得素材管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:material:query')")
    public CommonResult<MaterialRespVO> getMaterial(@RequestParam("id") Long id,HttpServletRequest request) {
        MaterialRespVO materialRespVO = materialService.getMaterialAndFileList(id);
        materialRespVO.setFirstFileUrl(getUrl(request,materialRespVO.getFirstFileUrl()));
        materialRespVO.setUrl(getUrl(request,materialRespVO.getFileUploadPath()));
        if(CollectionUtils.isNotEmpty(materialRespVO.getReleaseFileList())){
            for (MaterialReleaseFileRespVO materialReleaseFileRespVO : materialRespVO.getReleaseFileList()) {
                materialReleaseFileRespVO.setUrl(getUrl(request,materialReleaseFileRespVO.getFileUploadPath()));
            }
        }
        return success(materialRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得素材管理分页")
    @PreAuthorize("@ss.hasPermission('ai:material:query')")
    public CommonResult<PageResult<MaterialListVO>> getMaterialPage(@Valid MaterialPageReqVO pageReqVO,HttpServletRequest request) {
        PageResult<MaterialListVO> pageResult = materialService.getMaterialPage(pageReqVO);
        if(CollectionUtils.isNotEmpty(pageResult.getList())){
            for (MaterialListVO materialListVO : pageResult.getList()) {
                materialListVO.setUrl(getUrl(request,materialListVO.getFileUploadPath()));
                materialListVO.setFirstFileUrl(getUrl(request,materialListVO.getFirstFileUrl()));
            }
        }
        return success(BeanUtils.toBean(pageResult, MaterialListVO.class));
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出素材管理 Excel")
//    @PreAuthorize("@ss.hasPermission('ai:material:export')")
//    @ApiAccessLog(operateType = EXPORT)
//    public void exportMaterialExcel(@Valid MaterialPageReqVO pageReqVO,
//              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<MaterialListDO> list = materialService.getMaterialPage(pageReqVO).getList();
//        // 导出 Excel
//        ExcelUtils.write(response, "素材管理.xls", "数据", MaterialRespVO.class,
//                        BeanUtils.toBean(list, MaterialRespVO.class));
//    }

    /**
     * 根据相对路径获取可访问的路径
     * @param request
     * @param relativePath
     * @return
     */
    public String getUrl(HttpServletRequest request,String relativePath){
        if(null == relativePath){
            return null ;
        }
        String scheme = request.getScheme(); // 获取协议（http 或 https）
        String serverName = request.getServerName(); // 获取服务器地址
        int serverPort = request.getServerPort(); // 获取端口号
        String port = serverPort == 80 ? "" : ":" + serverPort;

        relativePath = relativePath.startsWith("/")?relativePath:("/"+relativePath);
        String serverUrl = scheme + "://" + serverName + port;
        return serverUrl+ "/"+materialFilePrePath+relativePath;
    }

}